<template>
  <div v-show="showPlayerUi" class="player">
    <audio
      ref="audio"
      v-show="currentPlayMusicUrl"
      @play="ready"
      @error="error"
      @ended="end"
      @paused="paused"
      @load="load"
      @timeupdate="updateTime"
      :src="currentPlayMusicUrl"
    />
    <div v-show="!$store.state.player.miniUi" @click="onClickMiniUi" class="miniUi">
      <img
        v-if="songPicUrl"
        :class="['play-ui-i', uiRool?'rotation':'']"
        :src="songPicUrl"
        alt="smusic img"
      >
      <div v-if="currentPlayMusic">
        <h4 v-text="songName +' '+ songAuthor" class="play-title" />
        <p class="tip">
          滑动自动切换上下首歌曲
        </p>
      </div>
      <span>
        <van-icon @click.native.stop="onClickPlayOrPause" :name="iconPlayOrPause" size="36" />
        <van-icon @click.native.stop="onClickList" class="play-ui-l icon" name="orders-o" />
      </span>
    </div>
    <van-popup v-model="$store.state.player.miniUi" class="bigUi">
      <div>
        <img
          :src="songPicUrl"
          alt="smusic img"
          class="player-bgimage"
        >
      </div>
      <div v-show="currentPlayMusic" class="player-header">
        <van-icon @click="onClickMiniUi" name="arrow-down" class="player-icon-back" />
        <div>
          <h4 v-text="songName" />
          <span v-text="songAuthor" />
        </div>
      </div>
      <div v-show="currentPlayMusic" class="player-content">
        <div class="song-box">
          <img
            v-if="imgLoadEnd"
            @load="onImgLoadEnd"
            :class="['song-icon', uiRool?'rotation':'']"
            :src="songPicUrl"
            alt="smusic img"
          >
        </div>
        <div class="song-ctl">
          <van-progress :percentage="currentRate" :show-pivot="false" stroke-width="8" />
          <ul>
            <li>循环</li>
            <li @click="pre">
              《《
            </li>
            <li @click="onClickPlayOrPause">
              <van-icon :name="iconPlayOrPause" size="36" />
            </li>
            <li @click="next">
              》》
            </li>
            <li @click="onClickList">
              列表
            </li>
          </ul>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { songLyric, songUrl } from '@/utils/api/song'

export default {
  data () {
    return {
      iconPlayOrPause: 'play-circle-o',
      play_t: '播放',
      currentPlayMusicUrl: '',
      currentPlayMusicLyric: {}, // 当前歌曲的歌词
      currentRate: 0.1, // 当前歌曲播放进度
      tempInterval: null, // 测试 定时器
      uiRool: false, // ui滚动控制
      currentPlayListIndex: 0, // 列表当前歌曲播放位置
      songPicUrl: '',
      songName: '',
      songAuthor: '',
      imgLoadEnd: false // 让图片加载完成才显示滚动背景
    }
  },
  computed: {
    showPlayerUi () {
      return this.$store.state.player.showPlayerUi
    },
    playList () {
      return this.$store.state.player.currentPlayList
    },
    currentPlayMusic () {
      // 当前播放的歌曲
      return this.$store.state.player.currentPlayObj
    },
    playing () {
      // 播放器正在播放状态
      return this.$store.state.player.isPlaying
    },
    _looping () {
      // 播放器循环播放模式
      return this.$store.state.player.isLoop
    },
    _random () {
      // 播放器循环随机播放模式
      return this.$store.state.player.isRandom
    }
  },
  watch: {
    async currentPlayMusic (val, old) {
      if (val.id !== old.id) {
        // 切换另外一首
        this.resetPlayer()
        try {
          this.songPicUrl = val.album.picUrl
          this.songName = val.name
          this.songAuthor = val.artists[0].name
        } catch (error) {}
        this.$store.commit('player/setIsPlaying', false)
        await this._play()
      }
    },
    async playing (val, oldVal) {
      await this.$nextTick()
      if (val) {
        this.audio.play()
        this.uiRool = true
        this.playBtnUiState(true)
      } else {
        this.audio.pause()
        this.uiRool = false
        this.playBtnUiState(false)
      }
    }
  },
  async mounted () {
    await this.$nextTick()
    this.audio = this.$refs.audio
  },
  methods: {
    onImgLoadEnd () {
      // eslint-disable-next-line no-console
      console.log('load')
      this.imgLoadEnd = true
    },
    onClickMiniUi () {
      // 点击 MiniUi
      this.$store.commit('player/setMiniUi', !this.$store.state.player.miniUi)
    },
    onClickPlayOrPause () {
      // 点击播放/暂停
      if (this.currentPlayMusicUrl) {
        this.$store.commit('player/setIsPlaying', !this.playing)
      }
    },
    async _play () {
      // 播放逻辑
      // 通过id 获取当前歌曲真实播放地址,歌词
      // 设置播放进度状态
      if (!this.currentPlayMusic) { return }
      const url = await this.getMusicUrl(this.currentPlayMusic.id)
      if (!url) {
        // 找不到播放的地址
        this.$toast('抱歉,找不到播放的地址')
        this.$store.commit('player/setIsPlaying', false)
        this.uiRool = false
        try {
          setTimeout(() => {
            this.next()
          }, 2000)
        } catch (error) {}
        return
      }
      this.getCurrentMusicIndexAtList()
      if (!this.currentPlayMusicUrl) {
        // 首次播放
        this.currentPlayMusicUrl = url
        this.$store.commit('player/setIsPlaying', true)
        this.uiRool = true
        return
      }
      if (this.currentPlayMusicUrl !== url) {
        // 切换歌曲
        this.ready()
        this.currentPlayMusicUrl = url
        this.$store.commit('player/setIsPlaying', true)
        this.uiRool = true
      }
    },
    async getMusicUrl (id) {
      // 通过id 获取当前歌曲真实播放地址
      try {
        const res = await songUrl([id])
        return res.data.data[0].url
      } catch (error) {}
    },
    async lyricUpdate (id) {
      // 获取歌词
      // 歌词播放同步
      const lyricRes = await songLyric(id)
      if (lyricRes.code !== 200) { return }
      this.currentPlayMusicLyric = lyricRes.lrc
    },
    onClickList () {
      // 点击当前播放列表
      // eslint-disable-next-line no-console
      console.log('当前播放列表')
      this.$toast('当前播放列表')
    },
    getMathRamdon (arr = []) {
      // 随机一个随机数
      return Math.floor(Math.random * arr.length)
    },
    exportPlayList () {
      // 随机播放一首歌曲
      this.currentPlayMusic = this.getMathRamdon(this.playList)
    },
    refreshPlayer () {
      this.currentRate = 0
    },
    resetPlayer () {
      // 刷新播放器
      this.currentRate = 0
      this.songPicUrl = ''
      this.songName = ''
      this.songAuthor = ''
      this.uiRool = false
    },
    async ready () {
      // eslint-disable-next-line no-console
      console.log('播放')
      await this.$nextTick()
      this.audio.play()
    },
    load () {
      // 重新加载
      this.audio.load()
    },
    paused () {
      this.$toast('暂停')
      this.audio.pause()
    },
    error () {
      // this.$toast('error')
    },
    end () {
      this.$toast('播放结束,自动切换下一首歌')
      this.$store.commit('player/setIsPlaying', false)
      this.next()
    },
    updateTime (e) {
      this.currentRate = parseInt((e.target.currentTime / this.currentPlayMusic.duration) * 100000)
    },
    next () {
      // 下一首 普通播放模式 循环播放模式 随机播放模式
      if (!this._looping) {
        // 正常播放模式
        if (this.playList.length === 1) {
          // 结束播放状态
          this.refreshPlayer()
        }
        if (this.currentPlayListIndex < this.playList.length - 1) {
          this.$store.commit('player/setCurrentPlayObj', this.playList[this.currentPlayListIndex + 1])
        } else {
          this.refreshPlayer()
        }
        return
      }
      if (this._looping) {
        // 循环播放模式
        if (this.playList.length === 1) {
          // 单曲 循环
          this.ready()
        }
        if (this.playList.length > 1) {
          // 根据当前播放歌曲在列表的位置 切换下一曲
          if (this.currentPlayListIndex < this.playList.length - 1) {
            this.$store.commit('player/setCurrentPlayObj', this.playList[this.currentPlayListIndex + 1])
          } else {
            // 最后一首播放完成 则重头开始播
            this.$store.commit('player/setCurrentPlayObj', this.playList[0])
          }
        }
        return
      }
      if (this._random) {
        const _length = this.playList.length || 0
        if (_length === 1) {
          // 单曲 循环
          this.ready()
        }
        if (_length > 1) {
          // 避免同曲重复播
          const tempList = this.playList.filter(item => item.id !== this.currentPlayMusic.id)
          const nextIndex = Math.floor(Math.random() * tempList.length)
          const nextObj = tempList[nextIndex]
          this.$store.commit('player/setCurrentPlayObj', nextObj)
        }
      }
    },
    pre () {
      // 上一首
      if (this._random) {
        // 随机模式
        this.next()
        return
      }
      if (this.currentPlayListIndex === 0) {
        return
      }
      this.$store.commit('player/setCurrentPlayObj', this.playList[this.currentPlayListIndex - 1])
    },
    playBtnUiState (bool) {
      this.play_t = bool ? '暂停' : '播放'
      this.iconPlayOrPause = bool ? 'pause-circle-o' : 'play-circle-o'
    },
    getCurrentMusicIndexAtList () {
      // 尝试获取当前播放的歌曲在播放列表中的序列位置
      this.currentPlayListIndex = this.playList.indexOf(this.currentPlayMusic)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/global.scss";

.player {
  width: 100%;
  .miniUi {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 9999;
    width: 100%;
    height: 60px;
    padding-left: 56px;
    padding-top: 8px;
    padding-right: 88px;
    background: #fff;
    border-top: 1px solid rgba(0,0,0,.2);
    border-top-right-radius: 16px;
    border-top-left-radius: 16px;
    box-sizing: border-box;
    opacity: .8;
    .icon {
      width: 44px;
      height: 44px;
      line-height: 44px;
      text-align: center;
      font-size: 32px;
      margin-top: 8px;
    }
    .play-ui-i {
      position: absolute;
      top: 6px;
      left: 6px;
      width: 44px;
      border-radius: 50%;
      background: #fff;
    }
    .play-ui-p {
      width: 35px !important;
      height: 35px !important;
      line-height: 35px !important;
    }
    span {
      position: absolute;
      top: 0;
      right: 0px;
    }
    .play-title {
      @include ellipsis;
    }
  }
  .bigUi {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    .player-bgimage {
      position: absolute;
      top: 0;
      left: 0;
      z-index: initial;
      filter: blur(25px) opacity(.7);
      width: 100%;
      height: 100%;
    }
    .player-header {
      width: 100%;
      height: 60px;
      padding: 0 10px;
      border-bottom: 1PX solid rgba(0,0,0,.1);
      box-shadow: 2px 1px 10px rgba(0,0,0,.2);
      display: inline-flex;
      flex-direction: row;
      align-items: center;
      .player-icon-back {
        font-size: 20px;
        margin: 0 20px 0 10px;
      }
      div {
        h4 {
          color: #333;
          font-size: 20px;
          font-weight: 600;
          @include ellipsis;
        }
        span {
          color: #999;
          font-size: 14px;
          @include ellipsis;
        }
      }
    }
    .player-content {
      width: 100%;
      height: calc(100% - 160px);
      text-align: center;
      .song-box {
        width: 100%;
        height: 100%;
        .song-icon {
          position: absolute;
          top: 20%;
          left: calc(50% - 160px);
          width: 320px;
          height: 320px;
          border-radius: 50%;
        }
      }
      .song-ctl {
          position: fixed;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 100px;
          line-height: 100px;
          box-sizing: border-box;
          opacity: .8;
          border-top: 1px solid red;
          ul {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-around;
            li {
              width: 36px;
              height: 36px;
              line-height: 36px;
              border-radius: 50%;
            }
          }
        }
    }
  }
}
</style>
